/**
 * Created by raphael on 15-8-5.
 */
var models = require('../models');
var express = require('express');
var bodyParser = require('body-parser');
var apiRouter = express.Router();

// create application/json parser
var jsonParser = bodyParser.json();

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({extended: false});

apiRouter.use(jsonParser);
apiRouter.use(urlencodedParser);

// welcome message
apiRouter.get('/', function (req, res) {
    res.json({
        message: 'welcome to api demo!'
    });
});

// on routes that end in /users
apiRouter.route('/users')
    .post(function (req, res) {
        models.User.create({
            username: req.param('username')
        }).then(function () {
            res.json({message: 'user ' + req.param('username') + ' add complete'});
        });
    })
    .get(function (req, res) {
        models.User.findAll().then(function (users) {
            res.json(users);
        });
    });

// on routes that end in /users/:user_id
apiRouter.route('/users/:user_id')
    .get(function (req, res) {
        models.User.findAll({
            where: {
                username: req.param('user_id')
            }
        }).then(function (user) {
            res.json(user);
        });
    })
    .delete(function (req, res) {
        models.User.destroy({
            where: {
                username: req.param('user_id')
            }
        }).then(function () {
            res.send('delete complete');
        });

    })
    .put(function (req, res) {
        models.User.update({
            username: req.body.username
        }, {
            where: {
                username: req.param('user_id')
            }
        });
    });

module.exports = apiRouter;
